'use strict'

class joke {
  constructor() {
    this.param = '/'
  }

  async get(c) {
    let ret = await c.service.psql.query(`select * from joke order by joke_id asc`)
    c.status(200).send(ret.rows)
  }

  async post(c) {
    var obj = c.body
    console.log(obj)
    if (obj) {
      var { joke_time, joke_content } = obj
      let row = await c.service.psql.query(`select * from joke order by joke_id asc`)
      let joke_id = parseInt(row.rows[row.rows.length - 1].joke_id) + 1
      console.log(joke_id, joke_time, joke_content)
      let ret = await c.service.psql.query(`insert into joke values('${joke_id}', '${joke_time}', '${joke_content}')`)
      console.log(ret)
      c.status(200).send('已接收')
    } else {
      c.status(400).send('please check your data :)')
    }
  }

  async delete(c) {
    if (!c.body.isRows) {
      var id = c.body.id
      console.log(id)
      if (id) {
        let ret = await c.service.psql.query(`delete from joke where joke_id like '${id}'`)
        let ret2 = await c.service.psql.query(`delete from collectjoke where collectjoke_id like '${id}'`)
        console.log(ret, ret2)
        c.send('已删除')

      } else {
        c.send('删除失败')
      }
    } else {
      var idArr = c.body.idArr
      console.log(idArr)
      for (let i = 0; i < idArr.length; i++) {
        let ret = await c.service.psql.query(`delete from joke where joke_id like '${idArr[i]}'`)
        let ret2 = await c.service.psql.query(`delete from collectjoke where collectjoke_id like '${idArr[i]}'`)
        console.log(ret, ret2)
      }
      c.send('complete')
    }
  }

  async put(c) {
    var req = c.body
    console.log(req)
    if (req.joke_time) {
      let ret = await c.service.psql.query(`update joke set joke_time = '${req.joke_time}' where joke_id like '${req.joke_id}'`)
      console.log('time', ret)
    }
    if (req.joke_content) {
      let ret = await c.service.psql.query(`update joke set joke_content = '${req.joke_content}' where joke_id like '${req.joke_id}'`)
      console.log('content', ret)
    }
    c.send('complete')
  }
}

module.exports = joke
